using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MultiAgentsServer.Scripts.Database;

namespace MultiAgentsServer.Pages;

[Authorize]
public class InviteManagerModel(DataBaseOperationService dbOperationService) : PageModel
{
    [BindProperty]
    public string InviteCode { get; private set; } = "";

    private readonly DataBaseOperationService _dbOperationService = dbOperationService;

    public void OnGet()
    {
        InviteCode = _dbOperationService.GetManagerInvitationCode();
    }

    public IActionResult OnPostRefreshInviteCode()
    {
        InviteCode = GenerateRandomString(6);
        _dbOperationService.UpdateInvitationCode(InviteCode);
        return Page();
    }

    public static string GenerateRandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }
}
